import { Menu, Icon, Card, Form, TimePicker, DatePicker, Select, Input, Button, Table, Pagination, InputNumber, message, Badge  } from "antd";
import moment from "moment";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import ProcessingDetail from "./processingDetail";
import { workOrderExport, workOrderProcessingList, workOrderSolutionDuration, workOrderUnReadNum } from "@/services/workOrder";
import UserSession from "@/UserSession";
import { adminList,allList } from "@/services/userProfile";
import { selfBuiltList } from "@/services/aigcUser";

class WorkOrderStatistics extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      type:'2',
      loading:false,
      current:1,
      size:10,
      total:0,
      list:[],
      userList:[],
      unReadNum:0
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    this.getList()
    this.getUserList()
    this.getUnReadNum()
  }

  getUserList = async () => {
    let userList = []
    if(UserSession.getCurrentUser().isAdmin){
      //甲方管理员
      const res = await adminList({current:1,size:999999,applicationId:UserSession.getCurrentUser().applicationId})
      userList =res.records
    }else{
      //乙方
      const res = await selfBuiltList({current:1,size:999999,categoryId:"",name:""})
      userList =res.records
    }
    
    this.setState({userList})
  }

  getList = () => {
    this.setState({
      loading:true,
    },async () => {
      const { current,size,type } = this.state;
      const formInfo = this.props.form.getFieldsValue()
      let orderFlag = UserSession.isAdmin ? 0 : 1
      if(type == -1){
        orderFlag = null
      }
      let obj = {
        current,
        size,
        search:formInfo.search,
        processUser:formInfo.processUser,
        createUser:formInfo.createUser,
        startDate:formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
        endDate:formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
        ticketStatus:type == -1 ? null : parseInt(type),
        applicationId:UserSession.getCurrentUser().applicationId,
        orderFlag
      }
      console.log('查询入参=======',obj);
      const res = await workOrderProcessingList(obj)
      
      this.setState({
        loading:false,
        list:res.records,
        total:res.total
      })
    })
  }

  doSearch = (current,size) => {
    this.setState({current,size},() => {
      this.getList()
    })
  }

  /**
   * 
   * @param {*} row 表格记录数据
   * @param {*} readonly 是否只读 true只读
   * @param {*} allocatedDisabled 是否禁用分配按钮 true禁用
   * @param {*} replayDisabled 是否禁用回复按钮 true禁用
   */
  openDetail = (row,readonly,allocatedDisabled,replayDisabled) => {
    // 如果工单状态是待处理或处理中，可以让顾问回复，显示回复框
    if (row.ticketStatus == 2 || row.ticketStatus == 3){
      this.ProcessingDetail.initData(row.id,readonly,allocatedDisabled,false)
    }else {
      this.ProcessingDetail.initData(row.id,readonly,allocatedDisabled,replayDisabled)
    }
  }

  handleClick = e => {
    this.setState({type:e.key},this.doSearch(1,this.state.size))
    
  }

  changeRow = (value,index,field) => {    
    let { list } = this.state;
    list[index] = {...list[index],[field]:value}    
    this.setState({list}) 
  }

  editTimes = async row => {
    const res = await workOrderSolutionDuration({id:row.id,solutionDuration:row.solutionDuration})
    message.info(res.message)
    this.getList()
  }

  doExport = async () => {
    const { current,size,type } = this.state;
    const formInfo = this.props.form.getFieldsValue()
    let orderFlag = UserSession.isAdmin ? 0 : 1
    if(type == -1){
      orderFlag = null
    }
    let obj = {
      current,
      size,
      search:formInfo.search,
      processUser:formInfo.processUser,
      startDate:formInfo.time && formInfo.time[0] ? moment(formInfo.time[0]).format("YYYY-MM-DD") : '',
      endDate:formInfo.time && formInfo.time[1] ? moment(formInfo.time[1]).format("YYYY-MM-DD") : '',
      ticketStatus:type == -1 ? null : parseInt(type),
      applicationId:UserSession.getCurrentUser().applicationId,
      orderFlag
    }
    const res = await workOrderExport(obj)
  }

  getUnReadNum = async () => {
    const res = await workOrderUnReadNum()
    this.setState({unReadNum:res.unReplyNum})
  }

  render(){
    const { type,current,size,list,total,loading,userList ,unReadNum} = this.state;
    const { form:{getFieldDecorator} } = this.props;
    
    let columns = [
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.companyName'}),
        dataIndex:"applicationName",
        width:180,
        fixed: 'left',
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.submitter'}),
        dataIndex:"submitUser",
        width:180,
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.orderNumber'}),
        dataIndex:"orderNum",
        width:170,
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.content'}),
        dataIndex:"content",
        width:600,
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.processUser'}),
        dataIndex:"processUser",
        width:150,
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.createTime'}),
        dataIndex:"createTime",
        width:150,
        render(time){
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({id: 'pages.workOrder.processing.table.lastProcessTime'}),
        dataIndex:"lastProcessTime",
        width:150,
        render(time){
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
    ]

    //待处理
    if(type == 2){
      columns.splice(4, 0, {
        title: formatMessage({id: 'pages.workOrder.processing.table.unProcessedUsers'}),
        dataIndex:"unProcessedUsers",
        width:150
      });
    }

    //已解决
    if(type == 4){
      columns.push({
        title:formatMessage({id: 'pages.workOrder.processing.table.companyProcessHours'}),
        dataIndex:"solutionDurationJiafang",
        width:100,
      },{
        title:formatMessage({id: 'pages.workOrder.processing.table.serviceProcessHours'}),
        dataIndex:"solutionDurationYifang",
        width:100,
      })
    }

    //全部
    if(type == -1){
      columns.splice(4, 0, {
        title: formatMessage({id: 'pages.workOrder.processing.table.processSide'}),
        dataIndex:"orderFlag",
        width:150,
        render:orderFlag => {
          return orderFlag == 0 ? formatMessage({id: 'pages.workOrder.processing.company'}) : formatMessage({id: 'pages.workOrder.processing.serviceSide'})
        }
      });
      columns.splice(5, 0, {
        title: formatMessage({id: 'pages.workOrder.processing.table.status'}),
        dataIndex:"ticketStatus",
        width:150,
        render:ticketStatus => {
          let statusKey = ''
          switch(ticketStatus){
            case 1:
              statusKey = 'pages.workOrder.processing.status.pendingAssign'
              break
            case 2:
              statusKey = 'pages.workOrder.processing.status.pendingProcess'
              break
            case 3:
              statusKey = 'pages.workOrder.processing.status.processing'
              break
            case 4:
              statusKey = 'pages.workOrder.processing.status.resolved'
              break
            case 5:
              statusKey = 'pages.workOrder.processing.status.canceled'
              break
            default:
              statusKey = ''
          }
          return statusKey ? formatMessage({id: statusKey}) : ''
        }
      },{
        title: formatMessage({id: 'pages.workOrder.processing.table.companyProcessTime'}),
        dataIndex:"solutionDurationJiafang",
        width:100,
      },{
        title: formatMessage({id: 'pages.workOrder.processing.table.serviceProcessTime'}),
        dataIndex:"solutionDurationYifang",
        width:100,
      });
    }

    columns.push({
      title: formatMessage({id: 'pages.workOrder.processing.table.actions'}),
      width:100,
      align:"center",
      fixed: 'right',
      render:(item,row) => {
        return row.ableProcess ? 
          <Button type="link" onClick={() => this.openDetail(row,false,false,!row.ableReply)}>
            {formatMessage({id: 'pages.workOrder.processing.process'})}
          </Button> : 
          <Button type="link" onClick={() => this.openDetail(row,true,true,true)}>
            {formatMessage({id: 'pages.workOrder.processing.button.view'})}
          </Button>
      }
    })


    return(
      <Card bordered={false} style={{height:"100%"}}>
        <Menu onClick={this.handleClick} selectedKeys={[type]} mode="horizontal">
          <Menu.Item key={'2'}>
            {formatMessage({id: 'pages.workOrder.processing.menu.pending'})}
          </Menu.Item>
          <Menu.Item key={'3'}>
            <Badge count={unReadNum} offset={[10,0]} overflowCount={99}>
              <span>{formatMessage({id: 'pages.workOrder.processing.menu.processing'})}</span>
            </Badge>
          </Menu.Item>
          <Menu.Item key={'4'}>
            {formatMessage({id: 'pages.workOrder.processing.menu.resolved'})}
          </Menu.Item>
          <Menu.Item key={'-1'}>
            {formatMessage({id: 'pages.workOrder.processing.menu.all'})}
          </Menu.Item>
        </Menu>

        <Form layout="inline" style={{margin:"20px 0"}}>
          <Form.Item>
            {getFieldDecorator("time")(<DatePicker.RangePicker style={{width:250}} />)}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("processUser")(
              <Select placeholder={formatMessage({id: 'pages.workOrder.processing.select.engineer'})} style={{width:250}}>
                <Select.Option value={null}>
                  {formatMessage({id: 'pages.workOrder.processing.select.all'})}
                </Select.Option>
                {
                  userList.map(item => (
                    <Select.Option value={item.id} key={item.id} title={item.name || item.userName}>{item.name || item.userName}</Select.Option>
                  ))
                }
              </Select>
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("search")(<Input.Search placeholder={formatMessage({id: 'pages.workOrder.processing.search.placeholder'})} style={{width:250}} onSearch={() => this.doSearch(1,size)} />)}
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={() => this.doSearch(1,size)}>
              {formatMessage({id: 'pages.workOrder.processing.button.search'})}
            </Button>
            {
              type == -1 ? <Button style={{marginLeft:8}} onClick={this.doExport}>
                {formatMessage({id: 'pages.workOrder.processing.button.export'})}
              </Button> : ''
            }
            
          </Form.Item>
        </Form>

        <Table 
          columns={columns}
          dataSource={list}
          rowKey={'id'}
          loading={loading}
          pagination={false}
          scroll={{x:"max-content",y:'calc(100% - 100px)'}}
        />

        {
          total < (size + 1) ? '' : (
            <div style={{textAlign:"right",marginTop:10}}>
              <Pagination 
                current={current}
                pageSize={size}
                total={total}
                showQuickJumper={true}
                onChange={this.doSearch}
              />
            </div>
          )
        }

        <ProcessingDetail onRef={ref => this.ProcessingDetail = ref} refreshList={() => this.doSearch(1,size)} refreshUnReadNum={this.getUnReadNum} />
      </Card>
    )
  }
}

export default Form.create()(WorkOrderStatistics)